public without sharing class CreateInstallApplyDetailController{
	public List<InstallApprovalDetailBean> iadList {get;set;}///带出的默认必备条件列表
	public List<InstallApprovalDetailBean> newiadList {get;set;}///带出的默认必备条件列表
    public String selectProduct {get;set;}//检索产品的关键字
    public List<ProductBean> pList {get;set;}//检索出来的产品
    public Boolean successCallBack {get;private set;}//成功回调
    public InstallApprovalDetail__c ap {get;set;}//批量修改的必备条件
    public InstallationApply__c insa {get;set;}//安装申请
    
    
    //筛选条件
    public String name { get; set; }//名称
    public String brand { get; set; }//品牌
    public String serial { get; set; }//货号
    public String nccode { get; set; } //产品编码
    public String category1 { get; set; } //一级分类
    public String category2 { get; set; }//二级分类
    public String category3 { get; set; }//三级分类
    
    public List<SelectOption> cate1Opts { get; private set; }//一级分类选项
    public List<SelectOption> cate2Opts { get; private set; }//二级分类选项
    public List<SelectOption> cate3Opts { get; private set; }//三级分类选项
    public List<SelectOption> link1Opts { get;set; }
    public List<SelectOption> link2Opts { get;set; }
    
    public String iadId {get;set;}//安装申请ID 
    public CreateInstallApplyDetailController(ApexPages.StandardController con){
        iadId = System.currentPageReference().getParameters().get('id');
        iadList = new List<InstallApprovalDetailBean>();
        newiadList = new List<InstallApprovalDetailBean>();
        pList = new List<ProductBean>();
        ap = new InstallApprovalDetail__c();
        
              //一级分类
        cate1Opts = new List<SelectOption>();
        cate1Opts.add(new SelectOption('', System.Label.Option_None));
        for (String str : System.Label.Product_Category1.split(',', -1)) {
            cate1Opts.add(new SelectOption(str, str));
        }
        
          // 二级分类
        cate2Opts = new List<SelectOption>();
        cate2Opts.add(new SelectOption('', System.Label.Option_None));
        for (String str : System.Label.Product_Category2.split(',', -1)) {
            cate2Opts.add(new SelectOption(str, str));
        }
            // 三级分类
        cate3Opts = new List<SelectOption>();
        cate3Opts.add(new SelectOption('', System.Label.Option_None));
        for (String str : System.Label.Product_Category3.split(',', -1)) {
            cate3Opts.add(new SelectOption(str, str));
        }
        
    }
    public void init(){
        insa = [select InstallsNumber__c from InstallationApply__c where Id =: iadId];
    ///加载默认的必备条件
        for(InstallApprovalDetail__c iad : [select Id,Name,Configuration__c,IsStandard__c,Amount__c,Remark__c,
          Configuration__r.Name,Configuration__r.Spec__c,Configuration__r.SerialNo__c,Outboundorder__c,Outboundorder__r.Name 
             ,Configuration__r.Brand__c,Description__c ,InventoryStatus__c,OrderMethod__c                                  
          from InstallApprovalDetail__c where InstallApproval__c =: iadId]){
        InstallApprovalDetailBean iab = new InstallApprovalDetailBean();
            iab.name = iad.Name;
            iab.productName = iad.Configuration__r.Name;
            iab.spec = iad.Configuration__r.Spec__c;
            iab.serialNo = iad.Configuration__r.SerialNo__c;
            iab.brand = iad.Configuration__r.Brand__c;
            iab.product = iad.Configuration__c;
            iab.IsStandard = iad.IsStandard__c;
            iab.amonut = iad.Amount__c;
            iab.inventoryStatus = iad.InventoryStatus__c;
            iab.outboundorder = iad.Outboundorder__c;
            iab.outboundorderName = iad.Outboundorder__r.Name;
            
            iab.iad = iad;
            iadList.add(iab);
        }
        
        
    }
    public void save(){
        Boolean flag = true;
    	for(InstallApprovalDetailBean ia: newiadList){
            try{

                if(ia.amonut == 0 ){
          		  		ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '数量不能为0!'));
                    	flag = false;
            			break;
           		 	}
            
            }catch(Exception e){
                flag = false;
              	  ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '数量必须为数字!'));

            }
            
			
        }
        if(flag == true){
       		List <InstallApprovalDetail__c> tempList = new List<InstallApprovalDetail__c>();
        	List<InstallApprovalDetailBean> temp = new List<InstallApprovalDetailBean>();
       		temp.addAll(newiadList);
            temp.addAll(iadList);
       		 Savepoint sp = Database.setSavepoint();
            try{
            	for(InstallApprovalDetailBean ia: temp){
            
            		
					/*if(ia.iad == null){
                		InstallApprovalDetail__c i = new InstallApprovalDetail__c();
                    	i.Name = ia.name;
                    	i.Configuration__c = ia.product;
                    	i.IsStandard__c = ia.IsStandard;
                    	i.Amount__c = ia.amonut;
                    	i.OrderMethod__c = ia.orderMethod;
                    	i.InventoryStatus__c = ia.inventoryStatus;
                    	i.Outboundorder__c = ia.outboundorder;
                        i.InstallApproval__c = iadId;
                    	tempList.add(i);
                     System.debug(i);
                    
                	}else{

               	 	} 
                    */
                    
                      //  ia.iad.OrderMethod__c = ia.orderMethod;
                   		//ia.iad.InventoryStatus__c =ia.inventoryStatus;
                   	 	//ia.iad.Outboundorder__c = ia.outboundorder;
                   // System.debug('***'+ia);
                		tempList.add(ia.iad);
                    
            	}
                System.debug('***'+tempList);

            	if(flag == true && tempList.size() > 0)upsert tempList;
                successCallBack = true;
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存成功!'));
            }catch(Exception e){
                	Database.rollback(sp);
                successCallBack = false;

                 	ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
            }
            
        	
        }

       
        
    
    }
    public void search(){
    Schema.DescribeSobjectResult m = Product__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
        
        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' from Product__c where Name != null';
        String whereStr = '';
        if (String.isBlank(name) == false) {
            whereStr += ' and Name like \'%' + name + '%\'';
        }
        if (String.isBlank(brand) == false) {
            whereStr += ' and  Brand__c like \'%' + brand + '%\'';
        }
        if (String.isBlank(serial) == false) {
            whereStr += ' and  SerialNo__c like \'%' + serial + '%\'';
        }
         if (String.isBlank(nccode) == false) {
            whereStr += ' and  NCCode__c like \'%' + nccode + '%\'';
        }
        if (String.isBlank(category1) == false) {
            whereStr += ' and  Category1__c like \'%' + category1 + '\'';
        }
        if (String.isBlank(category2) == false) {
            whereStr += ' and  Category2__c = \'' + category2 + '\'';
        }
         if (String.isBlank(category3) == false) {
            whereStr += ' and  Category3__c = \'' + category3 + '\'';
        }
     pList.clear();
    String cat2 = '';
        String cat3 = '';
        Set<String> cat2s = new Set<String>();
        Set<String> cat3s = new Set<String>(); 
        System.debug(sql + whereStr + ' limit 500');
    List<Product__c> pLists = Database.query(sql + whereStr + ' limit 500');
     for(Product__c p: pLists){
     ProductBean pb = new ProductBean();
        pb.chk = false;
        pb.p = p;
        pList.add(pb);

 if(p.Category2__c != null && p.Category2__c.length()>0)cat2s.add(p.Category2__c);
         if(p.Category3__c != null && p.Category3__c.length()>0)cat3s.add(p.Category3__c);
     }
       
        
            ///设置二级分类下拉列表
            for (String s : cat2s) {
                   cat2 = cat2 + s+ ',';
               
            }
            
            if(cat2.length()>1)cat2 = cat2.substring(0,cat2.length()-1);
            
               setLink1Opts(cat2);
         
            //设置三级级分类下拉列表
            for (String s : cat3s) {
                   cat3 = cat3 + s + ',';
               
            }
            if(cat3.length()>1)cat3 = cat3.substring(0,cat3.length()-1);
               
            setLink2Opts(cat3);
        
    }
    public void exchange(){
    
  // 去掉已勾选的意向产品
        List<InstallApprovalDetailBean> stayList = new List<InstallApprovalDetailBean>();
        for (InstallApprovalDetailBean ipb : newiadList) {
            if (ipb.chk == false) {
                stayList.add(ipb);
            }
        }
        
        newiadList.clear();
        newiadList.addAll(stayList);

        // 收集已选意向产品的产品Id
        Set<Id> existPid = new Set<Id>();
        for (InstallApprovalDetailBean ipb : newiadList) {
            existPid.add(ipb.product);
        }
        ///必备条件中已经存在的
        for (InstallApprovalDetailBean ipb : iadList) {
            existPid.add(ipb.product);
        }
        // 加入已勾选的产品
        for (ProductBean p : pList) {
            if (p.chk == true && existPid.contains(p.p.Id) == false) {
          InstallApprovalDetailBean ia = new InstallApprovalDetailBean();
                ia.chk = false ;
                
                InstallApprovalDetail__c iad = new InstallApprovalDetail__c();
                
                iad.Name = p.p.Name;
                iad.Configuration__c = p.p.Id;
                
                //iad.IsStandard__c = '可选项（非标配）';
                iad.Amount__c = 1;
                iad.InstallApproval__c = iadId;
                ia.iad = iad; 
                
                ia.name = p.p.Name;
                //ia.product = p.p.Id;
                ia.productName = p.p.Name;
                ia.spec = p.p.Spec__c;
                ia.serialNo = p.p.SerialNo__c;
                ia.brand = p.p.Brand__c;
               // ia.IsStandard = '可选项（非标配）';
                newiadList.add(ia);
            }
        } 
        if(pList.size() > 0 && newiadList.size()== 0){
          	ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '选择的产品已经存在!'));
        }
    }
    //获取选项列表
    private List<SelectOption> stringToSelectOption(String optStr){
    
       List<SelectOption> cateOpts = new List<SelectOption>();
      
       cateOpts.add(new SelectOption('', System.Label.Option_None));
       for (String str : optStr.split(',', -1)) {
            cateOpts.add(new SelectOption(str, str));
        }  
        return cateOpts; 
    }
    public void setLink2Opts(String  opt){
       link2Opts = stringToSelectOption(opt);
       if(pList.size()>0){
       cate3Opts = link2Opts ;
       }else{
       cate3Opts = getCate(3);
       }
    }
 public void setLink1Opts(String opt){
        link1Opts = stringToSelectOption(opt);
        if(pList.size()>0){
           cate2Opts = link1Opts;
        }else{
            cate2Opts = getCate(2);
        }
    }   
     private List<SelectOption> getCate(Integer i){
       String optStr = '';
       if(i == 0 ){
             optStr =  System.Label.Product_Category0;

       }else if(i == 1){
             optStr =  System.Label.Product_Category1;

       }else if(i == 2){
             optStr =  System.Label.Product_Category2;
       }else if(i == 3){
             optStr =  System.Label.Product_Category3;
       }         
             return stringToSelectOption(optStr);     
    }
    
    public class InstallApprovalDetailBean{
    	public Boolean chk {get;set;}//选中状态
        public InstallApprovalDetail__c iad {get;set;}//必备条件
        public String name {get;set;}//配置名称
        public String spec {get;set;}//规格
        public String serialNo {get;set;}//货号
        public String brand {get;set;}//品牌
        public String productName {get;set;}//配置产品名称
        public String product {get;set;}//配置产品Id 
        public String IsStandard {get;set;}//是否标配
        public Decimal amonut {get;set;}//数量
        public String orderMethod {get;set;}//订货方式
        public String inventoryStatus {get;set;}//库存状态
        public String outboundorder  {get;set;}//出库单Id
        public String outboundorderName {get;set;}//出库单名称
        
    }
    
    public class ProductBean{
    public Boolean chk {get;set;}//选中
        public Product__c p {get;set;}//产品
    
    }
}